const express = require('express')
const router = express.Router()
const db = require('../../../MySql')
const { formatDateTime } = require('../../utils/dateUtils')

router.post('/repo/paging', async (req, res) => {
    try {
        const rawTitle = req.body?.params?.title
        const title = (!rawTitle && rawTitle !== 0) ? '' : rawTitle

        const rawExcludes = req.body?.params.excludes
        let excludes = ''
        if (Array.isArray(rawExcludes)) {
            // 过滤掉空字符串和非数字值，然后拼接
            const validExcludes = rawExcludes.filter(item => item && !isNaN(item))
            excludes = validExcludes.join(',')
        } else if (rawExcludes && rawExcludes !== 0) {
            excludes = rawExcludes.toString()
        }

        let sql = `SELECT e.id,e.title,e.remark,e.create_time,e.update_time
            FROM el_repo e `//INNER JOIN el_exam_repo er ON er.repo_id=e.id
        let params = []

        if (title) {
            sql += ' where e.title LIKE ?'
            params.push(`%${title}%`)
        }

        if (excludes) {
            sql += ' where e.id not in (' + excludes + ')'
        }

        sql += ' ORDER BY e.create_time DESC'

        const [results] = await db.query(sql, params)

        //统计每个题库对应的单选题、多选题、判断题数量
        const records = await Promise.all(results.map(async (item) => {
            const [quTypeRes] = await db.query(`
                SELECT 
                    SUM(CASE WHEN qu_type=2 THEN 1 ELSE 0 END) as multiCount,
                    SUM(CASE WHEN qu_type=1 THEN 1 ELSE 0 END) as radioCount,
                    SUM(CASE WHEN qu_type=3 THEN 1 ELSE 0 END) as judgeCount
                FROM el_qu_repo 
                WHERE repo_id=?`, [item.id])

            return {
                "id": item.id,
                "code": "",
                "title": item.title,
                "remark": item.remark,
                "createTime": formatDateTime(item.create_time),
                "updateTime": formatDateTime(item.update_time),
                "multiCount": parseInt(quTypeRes[0]?.multiCount) || 0,
                "radioCount": parseInt(quTypeRes[0]?.radioCount) || 0,
                "judgeCount": parseInt(quTypeRes[0]?.judgeCount) || 0
            }
        }))

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "records": records,
                "total": records.length,
                "size": 10,
                "current": 1,
                "orders": [],
                "optimizeCountSql": true,
                "hitCount": false,
                "searchCount": true,
                "pages": Math.ceil(records.length / 10)
            },
            "success": true
        })
    } catch (error) {
        console.log(error)
        return res.status(500).json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})


module.exports = router
